<template>
	<view class="bg-light" style="height: 100%;">
		<tabsTop tabName="购物车"></tabsTop>
		<gwTitle title="合美供销云平台">
			<view class="pr-2" @click="handleEdit()">{{isEdit?'完成':'编辑'}}</view>
		</gwTitle>
		<!-- 购物车 -->
		<scroll-view scroll-y="true" class="w-100 shopCart" :style="'height:calc(100vh - 340rpx) '"
			style="margin-top: 130rpx;">
			<!-- 商品 -->
			<view class="py-2">
				<view v-for="(item,index) in ShopCar" :key="index" class="mx-2 py-2 bg-white rounded-lg mb-2">
					<view class=" flex align-center ">
						<view class="mx-2 flex-shrink">
							<uni-icons @click="handleSelect(item,index)" v-if="!item.isSelect" type="circle"
								color="#28a745" size="20"></uni-icons>
							<uni-icons @click="handleSelect(item,index)" v-else type="checkbox-filled" color="#28a745"
								size="20"></uni-icons>
						</view>
						<view class="mr-2 w-100">
							<view class="flex">
								<view class="flex-shrink rounded overflow-hidden"
									style="width: 180rpx; height: 180rpx;">
									<image :src="Domain_IMG+item.Picture_URL" class="img" mode="aspectFit"></image>
								</view>
								<view class="ml-2 flex flex-column justify-between w-100">
									<text>{{item.Article_Name}}</text>
									<view class="mr-2 font-sm rounded-lg flex justify-center align-center"
										style="background-color: rgb(247,248,250);width: 80rpx;height: 40rpx;"
										v-if="item.Specifications_Name">
										{{item.Specifications_Name}}
									</view>
									<view class="flex justify-between">
										<money :money="String(item.Amount)"></money>
										<counter
											@Count="handleCount($event,index,item.Article_SerialNumber,item.Sales_Unit_Price_Stock_SerialNumber)"
											:num="Number(item.Quantity)" :max="Number(item.Stock_Remain)"
											:loading="loading">
										</counter>
									</view>
								</view>
							</view>
						</view>
					</view>
					<view class="" style="background-color: white;border-radius: 20rpx;"
						v-if="item.Children.Gifts.length>0">
						<view class="flex justify-center align-center py-2" style="font-size: 35rpx;"
							@click="GiveOutFree(index)">
							{{item.GiveOut?"隐藏":"展示"}}赠品
						</view>
						<view v-for="(item1,index1) in item.Children.Gifts" :key="index1" class="flex mx-2"
							:class="index!=0?'':'mt-2'" style="background-color:#fafafa;" v-if="item.GiveOut">
							<view class="flex-shrink rounded overflow-hidden" style="width: 180rpx; height: 180rpx;">
								<image :src="Domain_IMG+item1.Picture_URL" class="img" mode=""></image>
							</view>
							<view class="ml-2 flex flex-column justify-between w-100 py-1">
								<text>{{item1.Article_Name}}</text>
								<view class="" v-if="item1.Specifications_Name">
									{{item1.Specifications_Name}}
								</view>
								<view class="flex justify-between">
									<money :money="item1.Sales_Unit_Price"></money>
									<view class="">
										数量:<text>{{item1.Quantity}}</text>
									</view>
									<!-- <counter @Count="handleCount($event,item1)" :num="item.Quantity"></counter> -->
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<!-- 底部操作 -->
		<view class="fixed-bottom xpy shadow flex align-center bg-white" style="height: 110rpx;">
			<!-- 按钮 -->
			<view class="ml-2 flex-shrink flex align-center ">
				<view @click="handleTotalSelect()" class="mr-2 flex-shrink">
					<uni-icons v-if="!isSelect" type="circle" color="#28a745" size="20"></uni-icons>
					<uni-icons v-else type="checkbox-filled" color="#28a745" size="20"></uni-icons>
				</view>
				<text class="font">全选</text>
			</view>
			<!-- 计算 -->
			<view v-if="!isEdit" class="w-100 flex justify-end mr-2">
				<!-- 费用 -->
				<view class="flex flex-column">
					<!-- 合计 -->
					<view class="flex justify-end align-end" style="height: 50%;">
						<text class="font-sm text-muted">不含运费</text>
						<text class="ml-2 font">合计：</text>
						<money :money="String(totalPrice)"></money>
					</view>
					<!-- 优惠 -->
					<view class="flex align-center" style="height: 50%;">
						<text class="font-sm text-muted">共优惠：￥0.00</text>
						<view class="ml-1 px-1 bg-hover-light rounded-circle flex align-center justify-center">
							<text class="font-sm">优惠明细</text>
							<uni-icons type="up" size="12"></uni-icons>
						</view>
					</view>
				</view>
				<!-- 按钮 -->
				<view @click="settlement(SelectShopCar)"
					class="ml-2 bg-success px-4 py-2 flex align-center rounded-circle">
					<text class="text-white font">去结算</text>
				</view>
			</view>
			<view v-else class="w-100 flex justify-end mr-2">
				<!-- 按钮 -->
				<view @click="Delete()" class="ml-2 bg-hover-light px-4 py-2 flex align-center rounded-circle">
					<text class="text-muted font">删除</text>
				</view>
			</view>
		</view>
		<!-- 付款二维码 -->
		<view class="zfAlert" v-if="dislogPayCode">
			<view class="flex justify-center">
				<Qrcode ref="qrcode" onval :val="goodsUrl" :size="300" :load-make="true" :show-loading="false" />
				<!-- <uqrcode ref="uqrcode" canvas-id="qrcode" :value="codeurl" :options="{ margin: 10 }">
				</uqrcode> -->
			</view>
			<view class="flex justify-center">
				<button @click="back()">返回上一页</button>
				<button :loading="loading" @click="CompletePayfor()">支付完成后点击此处</button>
			</view>
		</view>
	</view>
</template>

<script>
	const app = getApp();
	import tabsTop from "@/components/tabs/tabs-top.vue";
	import tabsBottom from "@/components/tabs/tabs-bottom.vue";
	import gwTitle from "@/components/gwtitle/gwTitle.vue"
	import money from "@/components/tool/money.vue";
	import counter from "@/components/tool/counter.vue";
	import Qrcode from "@/components/qrcode/qrcode.vue"
	import {
		GetChengXu,
		GetUrlLink,
		RedisAdd
	} from '@/api/global.js'
	import {
		getWX2CheckStockAction
	} from "@/api/article.js"
	import {
		DeleteShopCarQuantity,
		getShopCarAll,
		WX3ShopCarAll,
		editWXEditShopCarQuantity
	} from "@/api/article.js"
	import {
		accMul,
		accAdd,
		accSub
	} from "@/static/js/GeneralUtil.js"
	export default {
		components: { //轮播图组件
			tabsTop, //顶部导航栏
			gwTitle, //顶部跳转
			money, //钱样式
			counter, //计数器
			Qrcode // 二维码
		},
		data() {
			return {
				Domain_IMG: app.globalData.Domain_IMG, //图片地址
				screenWidth: uni.getSystemInfoSync().windowWidth,
				isEdit: false, //编辑
				ShopCar: [], //购物车中商品
				isSelect: true, //全选
				DeleteShopCar: [], //被选择删除
				SelectShopCar: [], //被选中提交
				totalPrice: 0,
				GiftstotalPrice: 0, // 赠品总价格
				loading: false,
				goodsUrl: '',
				dislogPayCode: false, // 支付弹窗
			}
		},
		onLoad() {
			// this.getData();
		},
		onShow(){
			this.getData();
		},
		methods: {
			// 加送商品是否显示
			GiveOutFree(index) {
				this.$set(this.ShopCar[index], 'GiveOut', !this.ShopCar[index].GiveOut)
			},
			handleEdit() {
				this.isEdit = !this.isEdit
				if (this.isEdit) {
					this.ShopCar.forEach((item, index) => {
						this.$set(item, 'isSelect', false)
						// item.isSelect = false
					})
					this.isSelect = false;
				} else {
					this.ShopCar.forEach(item => {
						// item.isSelect = true
						this.$set(item, "isSelect", true)
					})
					this.DeleteShopCar = []; //清空删除
					this.isSelect = true;
				}
			},
			// 修改购物车商品数量
			async editWXEditShopCarQuantity(Article_SerialNumber, Quantity) {
				const res = await editWXEditShopCarQuantity({
					Article_SerialNumber,
					Quantity,
					Open_ID: app.globalData.Open_ID,
					Type: 2
				})
				return res
			},
			async handleCount(e, index, Article_SerialNumber, Sales_Unit_Price_Stock_SerialNumber) { //计算数量
				if (!this.loading) {
					uni.showLoading({
						title: "加载中...",
					});
					this.loading = true;
					if (this.ShopCar[index].Stock_Remain > e) {
						var res = await this.editWXEditShopCarQuantity(Article_SerialNumber, e)
						if (res) {
							this.ShopCar[index].Quantity = e;
							this.ShopCar[index].Amount = accMul(e, this.ShopCar[index].Sales_Unit_Price)
							if (this.ShopCar[index].Children.Gifts.length > 0) {
								// 如果当前商品下的赠品数量大于0 每个赠品   目前只考虑了1比1
								this.ShopCar[index].Children.Gifts.forEach((item, index) => {
									item.Quantity = e
									item.Amount = accMul(e, item.Sales_Unit_Price)
									console.log(item, '当前赠品信息');
								})
							}
							uni.hideLoading();
							uni.showToast({
								title: '修改成功！',
								icon: 'success'
							})
							this.loading = false;
						} else {
							uni.hideLoading();
							uni.showToast({
								title: '修改失败！',
								icon: 'error',
							})
							this.loading = false;
						}
					} else {
						uni.showToast({
							title: '已达到最大值!',
							icon: 'error',
						})
						this.$set(this.ShopCar[index], "Quantity", this.ShopCar[index].Stock_Remain)
						await this.editWXEditShopCarQuantity(Article_SerialNumber, this.ShopCar[index].Quantity)
						this.ShopCar[index].Amount = accMul(this.ShopCar[index].Quantity, this.ShopCar[index]
							.Sales_Unit_Price)

						this.loading = false;
					}
				} else {
					uni.showToast({
						title: '正在修改中!!',
						icon: 'error',
					})
					this.loading = false;
				}
				this.getTotalPrice()

			},
			// CountTypeClick(e, Article_SerialNumber) {
			// 	console.log(e, Article_SerialNumber);
			// },
			handleSelect(item, Shop_index) { //选中商品
				item.isSelect = !item.isSelect
				this.$set(this.ShopCar, Shop_index, item)
				//判断是否全部选中
				if (this.ShopCar.some(item => !item.isSelect)) {
					this.isSelect = false
				} else {
					this.isSelect = true
				}
				if (!this.isEdit) { //选中
					if (item.isSelect) {
						this.SelectShopCar.push(item)
					} else {
						this.SelectShopCar = this.SelectShopCar.filter(i => i.Sales_Order_SerialNumber != item
							.Sales_Order_SerialNumber)
					}
				} else { //删除	
					if (item.isSelect) {
						this.DeleteShopCar.push(item.Sales_Order_SerialNumber)
					} else {
						this.DeleteShopCar = this.DeleteShopCar.filter(i => i != item.Sales_Order_SerialNumber)
					}
				}
				this.getTotalPrice();
			},
			// 获取总价
			getTotalPrice() {
				this.totalPrice = 0
				this.GiftstotalPrice = 0
				for (var i = 0; i < this.SelectShopCar.length; i++) {
					if (this.SelectShopCar[i].Children.Gifts.length > 0) {
						this.SelectShopCar[i].Children.Gifts.forEach(item => {
							this.GiftstotalPrice = accAdd(item.Amount, this.GiftstotalPrice)
						})
					}
					this.totalPrice = accAdd(this.SelectShopCar[i].Amount, this.totalPrice)
				}
				this.totalPrice = accAdd(this.GiftstotalPrice, this.totalPrice)
				console.log(this.totalPrice);
			},
			handleTotalSelect() {
				this.isSelect = !this.isSelect
				if (!this.isEdit) { //下单
					if (this.isSelect) { //全部选中
						this.ShopCar.forEach(item => {
							item.isSelect = true;
							this.SelectShopCar.push(item)
						})
					} else { //全部取消
						this.ShopCar.forEach(item => {
							item.isSelect = false;
						})
						this.SelectShopCar = []
					}
				} else { //删除
					if (this.isSelect) { //全部选中
						this.ShopCar.forEach(item => {
							item.isSelect = true;
							this.DeleteShopCar.push(item.Sales_Order_SerialNumber)
						})
					} else { //全部取消
						this.ShopCar.forEach(item => {
							item.isSelect = false;
						})
						this.DeleteShopCar = []
					}
				}
				this.getTotalPrice();
			},
			async settlement(SelectShopCar) {
				var selectShopCar = encodeURIComponent(JSON.stringify(SelectShopCar))
				// let data = await GetChengXu();
				if (app.globalData.isPC) {
					if (this.screenWidth > 800) {
						let ID_Code_Key = app.globalData.Open_ID == "" ? app.globalData.Tourist_Code : app.globalData
							.Open_ID
						let resRedis = await RedisAdd({
							Key: ID_Code_Key,
							Main: selectShopCar,
							Expire: 600
						})
						this.goodsUrl = await GetUrlLink('pages/shopCart/submitOrder', 1, '&ID_Code_Key=' +
							ID_Code_Key+ '&totalPrice=' +
							this.totalPrice)
						if (this.goodsUrl) {
							uni.showToast({
								title: '加载中',
								duration: 1000,
								icon: "loading"
							})
							this.dislogPayCode = true
						}
						console.log(this.goodsUrl);
					}
				} else {
					console.log(SelectShopCar, '选中的商品');
					uni.navigateTo({
						url: '/pages/shopCart/submitOrder?SelectShopCar=' + selectShopCar + '&totalPrice=' +
							this.totalPrice
					})
				}

			},
			// 获取购物车中的商品
			async getData() {
				let resData = [];
				let Tourist_Code = '';
				let Open_ID = '';
				if (app.globalData.Open_ID == "") {
					Tourist_Code = app.globalData.Tourist_Code
				} else {
					Open_ID = app.globalData.Open_ID
				}
				resData = await WX3ShopCarAll({
					Open_ID: Open_ID,
					Tourist_Code: Tourist_Code,
					App_ID: app.globalData.App_ID,
					Enterprise_Info_SerialNumber: app.globalData.Enterprise_Info_SerialNumber
				})
				console.log('看看购物车里有什么', resData);
				let res = [];
				if (resData.Status == 'success') {
					resData.Data.forEach((item, index) => {
						if (item.Children.Gifts.length > 0) {
							item.Children.Gifts.forEach((item1, index1) => {
								item1.Quantity = item.Quantity
								item1.Amount = accMul(item1.Quantity, item1.Sales_Unit_Price)
							})
						}
						item.GiveOut = false;
						res.push(item)
					})
				}
				// const res = await getShopCarAll({
				// 	Open_ID: app.globalData.Open_ID,
				// 	App_ID: app.globalData.App_ID,
				// 	Enterprise_Info_SerialNumber: app.globalData.Enterprise_Info_SerialNumber
				// })
				if (res.length > 0) {
					this.ShopCar = res
					this.SelectShopCar = res
				}
				for (var i = 0; i < this.ShopCar.length; i++) {
					this.ShopCar[i].isSelect = true;
					this.ShopCar[i].Stock_Remain = 1000
					this.getTotalPrice()
				}
				return res;
			},
			async Delete() { //购物车批量删除
				uni.showLoading({
					title: "加载中...",
				});
				this.loading = true;
				if (this.DeleteShopCar.length > 0) {
					await DeleteShopCarQuantity({
						Open_ID: app.globalData.Open_ID,
						Sales_Order_SerialNumber: JSON.stringify(this.DeleteShopCar)
					})
					const res = await this.getData();
					if (res.length == 0) {
						this.ShopCar = [];
						this.totalPrice = 0;
						this.SelectShopCar = [];
					} else {
						res.forEach((item, index) => {
							this.$set(this.ShopCar, index, item)
						})
						// this.ShopCar = res
						console.log(this.ShopCar, "购物车");
						this.SelectShopCar = res
						for (var i = 0; i < this.ShopCar.length; i++) {
							this.ShopCar[i].isSelect = false;
							await this.getTotalPrice()
						}
					}
					uni.hideLoading();
					uni.showToast({
						title: '删除成功！',
						icon: 'success'
					})
					this.loading = false;

				} else {
					uni.hideLoading();
					uni.showToast({
						title: '没有选择商品!',
						icon: 'error'
					})
					this.loading = false;
				}
			}

		}
	}
</script>

<style lang="scss" scoped>
	.zfAlert {
		position: fixed;
		top: 0;
		left: 0;
		bottom: 0;
		right: 0;
		margin: auto;
		z-index: 10000;
		background-color: #00000099;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}

	.shop-cart {
		width: 100%;

		.btn-left {
			padding: 0;
			margin: 0;
			width: 45%;
			border-radius: 0;
			border-top-left-radius: 50rpx;
			border-bottom-left-radius: 50rpx;
			background-color: #383838;
		}

		.btn-right {
			padding: 0;
			margin: 0;
			width: 45%;
			border-radius: 0;
			border-top-right-radius: 50rpx;
			border-bottom-right-radius: 50rpx;
			background-color: #09BB07;
		}
	}

	.fixed-top {
		top: 20px !important;
	}

	@media screen and (max-width:480px) {
		.shopCart {
			margin-top: 20rpx !important;
		}
	}

	@media (min-width: 768px) {}
</style>